package com.ling.module1sbbyyds.service.video;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.yitter.idgen.YitIdHelper;
import com.ling.sbbyyds.entity.users.User;
import com.ling.sbbyyds.entity.video.Video;
import com.ling.sbbyyds.entity.video.VideoLike;
import com.ling.sbbyyds.interaction.vo.videovo.VideoVo;
import com.ling.sbbyyds.interaction.param.VideoPo;
import com.ling.module1sbbyyds.service.news.usercenter.UserAttService;
import com.ling.module1sbbyyds.utils.FileLocalStorageTool;
import com.ling.module1sbbyyds.utils.ListBeanUtils;
import com.ling.module1sbbyyds.utils.UserThreadLocal;
import com.ling.sbbyyds.common.QueryApiUtils;
import com.ling.sbbyyds.imagetools.ImageUtils;
import com.ling.sbbyyds.interaction.ResultVo;
import com.ling.sbbyyds.mapper.user.UserMapper;
import com.ling.sbbyyds.mapper.video.SbbVideoLikeMapper;
import com.ling.sbbyyds.mapper.video.VideoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 视频
 */

@Service
public class VideoService {

    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAttService attService;
    @Autowired
    private SbbVideoLikeMapper videoLikeMapper;
    @Autowired
    private FileLocalStorageTool fileLocalStorageTool;

    /**
     * 帖子图片 存储文件夹
     */
    private static String POSTS_IMAGE_PATH = "articleFile";


    /**
     * 发布视频
     * form-data请求，，携带图片文件
     *
     * @param videoPo   视频信息参数
     * @param file     视频文件
     * @return 成功反馈
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultVo releaseVideo(VideoPo videoPo, MultipartFile file) throws Exception {
        Video video = new Video();
        BeanUtils.copyProperties(videoPo, video);

        //存在图片就进行上传
        String filePath;
        if (!ObjectUtils.isEmpty(file)) {
            if(!FileLocalStorageTool.isVideo(file)){
                return ResultVo.fail("请上传视频类型");
            }
            filePath = fileLocalStorageTool.uploadImage(POSTS_IMAGE_PATH, 2, file);
            video.setVideoUrl(filePath);
        }else {
            return ResultVo.fail("视频为空");
        }

        // 获取发布者
        Map<String, Object> userData = UserThreadLocal.get();
        User user = (User) userData.get("user");
        //设置文章id
        long newId = YitIdHelper.nextId();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String ipAddress = new QueryApiUtils().getIpAddress((String) userData.get("ip"));

        video.setId(newId)
                .setReleaseTime(sdf.parse(sdf.format(System.currentTimeMillis())))
                .setAuthorId(user.getId())
                .setIpAddress(ipAddress);
        videoMapper.insertSelective(video);
        //插入帖子成功
        return ResultVo.success(newId, "发布成功！");
    }

    /**
     * 获取视频列表
     *
     * @return
     */
    public ResultVo getVideoList(Integer page, Integer limit){
        List <VideoVo> videoVoList = null;
        int count = 0;
        try {
            Example example = new Example(Video.class);

            //进行分页查找
            List<Video> videoList;
            if (!ObjectUtils.isEmpty(page) && !ObjectUtils.isEmpty(limit)) {
                final PageInfo<Video> pageInfo = PageHelper.startPage(page, limit)
                        .doSelectPageInfo(() -> this.videoMapper.selectByExample(example));
                videoList = pageInfo.getList();
            } else {
                //不分页
                videoList = videoMapper.selectByExample(example);
            }

            if(!ObjectUtils.isEmpty(videoList)){
                videoVoList = new ArrayList<>(videoList.size());
                BeanUtils.instantiateClass(ListBeanUtils.class).copyList(videoList, videoVoList, VideoVo.class);

                Map<String, Object> userData = UserThreadLocal.get();
                Long userId = null;
                if(!ObjectUtils.isEmpty(userData)){
                    User userInfo = (User) userData.get("user");
                    if(!ObjectUtils.isEmpty(userInfo)){
                        userId = userInfo.getId();
                    }
                }

                for (VideoVo videoVo : videoVoList) {
                    if(!ObjectUtils.isEmpty(userId)){
                        videoVo.setIsAtt(attService.getAttUserFlag(userId, videoVo.getAuthorId(), true));
                        videoVo.setIsLike(videoLikeMapper.isLikeVideo(videoVo.getId(), userId) > 0);
                    }else {
                        videoVo.setIsAtt(false);
                        videoVo.setIsLike(false);
                    }
                    User user = userMapper.selectUserInfo(videoVo.getAuthorId());
                    videoVo.setHeadImage(ImageUtils.convertImageUrl(user.getAvatar()));
                    videoVo.setUserName(user.getUserName());
                    videoVo.setVideoUrl(ImageUtils.convertImageUrl(videoVo.getVideoUrl()));
                    videoVo.setBgmUrl(ImageUtils.convertImageUrl(videoVo.getBgmUrl()));
                    //评论数
                    videoVo.setReplyNum(0L);
                }
            }else {
                new ArrayList<>(0);
            }

            count = videoMapper.selectCountByExample(example);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ResultVo.success(videoVoList).put("count", count);
    }

    /**
     * 点赞视频
     *
     * @param videoLike 内容
     * @param type      true：点赞  false：取消点赞
     * @return
     */
    public ResultVo likeVideo(VideoLike videoLike, Boolean type) {
        //查询帖子点赞数和id
        Video video = videoMapper.getVideoLikeNum(videoLike.getVideoId());

        if (ObjectUtils.isEmpty(video)) {
            return ResultVo.fail("视频不存在");
        }

        // 获取用户id
        Map<String, Object> userData = UserThreadLocal.get();
        User user = (User) userData.get("user");
        videoLike.setUserId(user.getId());

        //是否点赞
        Integer likeReply = videoLikeMapper.isLikeVideo(video.getId(), user.getId());

        // 点赞
        if (type) {
            if(likeReply > 0){
                return ResultVo.fail("你已点赞");
            }
            videoLike.setId(YitIdHelper.nextId());
            video.setLikeNum(video.getLikeNum() + 1);
            videoLikeMapper.insert(videoLike);
        } else {
            if(likeReply <= 0){
                return ResultVo.fail("你未点赞");
            }
            // 取消点赞
            video.setLikeNum(video.getLikeNum() - 1);

            //删除点赞记录
            Example example = new Example(VideoLike.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("videoId", videoLike.getVideoId());
            criteria.andEqualTo("userId", videoLike.getUserId());
            videoLikeMapper.deleteByExample(example);
        }

        videoMapper.updateByPrimaryKeySelective(video);
        return ResultVo.success("true");
    }


}
